const express = require('express')
const router = express.Router()
const models = require('../models')
const getTotal = require('../utils/get-total')
const {success, error} = require('../utils/message')

// 购物车列表
router.get('/', async function (req, res, next) {
    const carts = await models.Cart.findAll({
        where: { userId: req.decoded.user.id },
        include: [{
            model: models.Product,
            as: 'product'
        }],
    })

    const data = {
        carts: carts,
        total: getTotal(carts)
    }
    return success(res, '查询成功！', data)
})

// 添加到购物车
router.post('/', async function (req, res, next) {
    const productId = req.body.productId

    if (!productId) return error(res, '商品不存在！')

    // 查询商品
    const product = await models.Product.findOne({where: {id: productId}})
    if (!product) {
        return error(res, '商品不存在！')
    }

    // 查询购物车
    const data = {
        userId: req.decoded.user.id,
        productId: productId
    }

    let cart = await models.Cart.findOne({where: data})

    // 如果不存在就创建
    if (!cart) {
        cart = await models.Cart.create(data)
    } else {
        // 商品数量 + 1
        await cart.increment('num')
        cart = await models.Cart.findOne({where: data})
    }

    return success(res, '添加购物车成功！', {cart})
})

// 修改购物车数量
router.patch('/:id', async function (req, res, next) {
    const id = req.params.id
    const type = req.body.type

    let cart = await models.Cart.findByPk(id)

    // 如果是增加数量
    if (type == 'inc') {
        await cart.increment('num')
    } else {
        cart.num != 1 && await cart.decrement('num')
    }

    cart = await models.Cart.findByPk(id)
    return success(res, '修改数量成功！', { cart })
})

// 删除
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id

    const cart = await models.Cart.findByPk(id)
    if (!cart) {
        return error(res, '当前购物车商品不存在，无法删除')
    }

    cart.destroy()
    success(res, '删除成功')
})

module.exports = router
